import config from "@/config";
import cookies from 'js-cookie';

export class FetchService {
  private requestInterceptors: Array<(url: string, options: RequestInit) => void> = [];
  private responseInterceptors: Array<(response: Response) => void> = [];

  async get<T>(url: string, data?: any): Promise<T> {
    return this._request('GET', url, data);
  }

  async post<T>(url: string, body: any): Promise<T> {
    return this._request('POST', url, body);
  }

  async form<T>(url: string, body: FormData): Promise<T> {
    return this._request('FORM', url, body);
  }

  async put<T>(url: string, body: any): Promise<T> {
    return this._request('PUT', url, body);
  }

  async delete<T>(url: string): Promise<T> {
    return this._request('DELETE', url);
  }

  addRequestInterceptor(interceptor: (url: string, options: RequestInit) => void) {
    this.requestInterceptors.push(interceptor);
  }

  addResponseInterceptor(interceptor: (response: Response) => void) {
    this.responseInterceptors.push(interceptor);
  }

  private async _request<T>(method: string, url: string, body?: any): Promise<T> {
    let _url = config.baseUrl + url;
    let headers: Record<string, string> = {};

    if (method === 'FORM') {
      // 不要手动设置 Content-Type
      headers = {};
    } else {
      headers = {
        'Content-Type': 'application/json'
      };
    }

    let options: RequestInit = {
      method: method,
      headers: headers
    };

    if (body) {
      if (method === 'GET') {
        if (Object.keys(body).length > 0) {
          _url += `?${new URLSearchParams(body)}`;
        }
      } else if (method === 'FORM') {
        options.body = body;
        options.method = 'POST';
      } else {
        options.body = JSON.stringify(body);
      }
    }

    this.runRequestInterceptors(_url, options);
    console.log(options,'options')
    const response = await fetch(_url, options);
    this.runResponseInterceptors(response);

    if (!response.ok) {
      const errorData = await response.json(); // 假设服务器返回 JSON 格式的错误信息
      throw new Error(errorData.message || response.statusText);
    }

    const data: T = await response.json();
    return data;
  }

  private runRequestInterceptors(_url: string, options: RequestInit) {
    if (!options.headers) {
      options.headers = {} as HeadersInit;
    }
    (options.headers as Record<string, string>)['authorization'] = cookies.get('token') || '';
    this.requestInterceptors.forEach(interceptor => interceptor(_url, options));
  }

  private runResponseInterceptors(response: Response) {
    this.responseInterceptors.forEach(interceptor => interceptor(response));
  }
}

// 使用示例
